package org.tinygroup.uiml.fileprocessor;

import org.tinygroup.fileresolver.impl.AbstractFileProcessor;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.uiml.UimlEngine;
import org.tinygroup.uiml.config.Styles;
import org.tinygroup.vfs.FileObject;
import org.tinygroup.xstream.XStreamFactory;

import com.thoughtworks.xstream.XStream;

public class UimlStylesFileProcessor extends AbstractFileProcessor {

	private static final String STYLES_EXT_FILENAME = ".styles.xml";

	private UimlEngine uimlEngine;

	public UimlEngine getUimlEngine() {
		return uimlEngine;
	}

	public void setUimlEngine(UimlEngine uimlEngine) {
		this.uimlEngine = uimlEngine;
	}

	public boolean isMatch(FileObject fileObject) {
		return fileObject.getFileName().endsWith(STYLES_EXT_FILENAME);
	}

	public void process() {
		XStream stream = XStreamFactory
				.getXStream(UimlEngine.XSTREAM_PACKAGENAME);
		for (FileObject fileObject : deleteList) {
			logger.logMessage(LogLevel.INFO, "正在删除样式配置文件[{0}]",
					fileObject.getAbsolutePath());
			Styles styles = (Styles) caches.get(fileObject
					.getAbsolutePath());
			if (styles != null) {
				uimlEngine.removeStyle(styles);
				caches.remove(fileObject.getAbsolutePath());
			}
			logger.logMessage(LogLevel.INFO, "删除样式配置文件[{0}]结束",
					fileObject.getAbsolutePath());
		}
		for (FileObject fileObject : changeList) {
			logger.logMessage(LogLevel.INFO, "正在读取样式配置文件[{0}]",
					fileObject.getAbsolutePath());
			Styles oldStylesType = (Styles) caches.get(fileObject
					.getAbsolutePath());
			if (oldStylesType != null) {
				uimlEngine.removeStyle(oldStylesType);
			}
			Styles styles = (Styles) stream.fromXML(fileObject
					.getInputStream());
			uimlEngine.addStyle(styles);
			caches.put(fileObject.getAbsolutePath(), styles);
			logger.logMessage(LogLevel.INFO, "读取样式配置文件[{0}]结束",
					fileObject.getAbsolutePath());
		}
	}

}
